import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { hideLoading } from '@/utils/loading'

axios.defaults.sendSuscced = true
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 15000
})
let retry = 1
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    hideLoading()
    return Promise.reject(error)
  }
)

service.interceptors.response.use(

  response => {
    const res = response.data
    if (res.code === '0000' || res instanceof Blob) { // 成功
      return res
    } else {
      hideLoading()
      if (res.code === '999') {
        if (retry > 0) {
          MessageBox.confirm('登录已失效，为不影响您的正常使用，请重新登录', '注销登录', {
            confirmButtonText: '重新登录',
            showCancelButton:false,
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
          retry--
        }
      }
      new Error(res.msg || 'Error')
      return Promise.reject(res)
    }
  },
  error => {
    //如果超时，则重新请求
    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
      Message({
        message: '请求超时，请重试！',
        type: 'error',
        duration: 5 * 1000
      })
      // return new service(error.config)
      hideLoading()
    }
    Message({
      message: error,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
